/**************************************************************************************************
 * light library                                                                                  *
 * Copyright © 2012 David Kretzmer                                                                *
 *                                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software  *
 * and associated documentation files (the "Software"), to deal in the Software without           *
 * restriction,including without limitation the rights to use, copy, modify, merge, publish,      *
 * distribute,sublicense, and/or sell copies of the Software, and to permit persons to whom the   *
 * Software is furnished to do so, subject to the following conditions:                           *
 *                                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies or       *
 * substantial portions of the Software.                                                          *
 *                                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING  *
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND     *
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.        *
 *                                                                                                *
 *************************************************************************************************/

#pragma once

#include <ostream>
#include <vector>
#include <stdexcept>
#include <algorithm>

#include "light/light.hpp"


namespace light
{
namespace io
{
	//=============================================================================================
	// An unbuffered output stream buffer that works as a container for streambufs, so it is
	// possible to write to multiple buffers with the same stream simultanously.
	//=============================================================================================
	template<typename CharType, typename TraitsType = ::std::char_traits<CharType> >
	class basic_containerbuf : public ::std::basic_streambuf<CharType, TraitsType>
	{
	public:
		typedef ::std::basic_streambuf<CharType, TraitsType> base_streambuf_type;

		typedef typename base_streambuf_type::char_type char_type;
		typedef typename base_streambuf_type::int_type int_type;
		typedef typename base_streambuf_type::pos_type pos_type;
		typedef typename base_streambuf_type::off_type off_type;
		typedef typename base_streambuf_type::traits_type traits_type;

	public:
		//---------------------------------------------------------------------
		// Constructor
		//---------------------------------------------------------------------
		basic_containerbuf() : base_streambuf_type()
		{

		}

		//---------------------------------------------------------------------
		// Constructor - adds the given streambuf to the list of buffers
		//---------------------------------------------------------------------
		explicit basic_containerbuf(base_streambuf_type *buffer) :
			base_streambuf_type()
			//, m_buffers(buffer, buffer+1)
		{
			m_buffers.push_back(buffer);
		}

		//---------------------------------------------------------------------
		// Move constructor
		//---------------------------------------------------------------------
		basic_containerbuf(basic_containerbuf &&rhs) :
			base_streambuf_type(), // Since this is an unbufffered streambuf,
			                       // all pointers are always null, so we don't have to move them.
			m_buffers(::std::move(rhs.m_buffers))
		{

		}

		//---------------------------------------------------------------------
		// Move assignment operator
		//---------------------------------------------------------------------
		basic_containerbuf& operator = (basic_containerbuf &&rhs)
		{
			m_buffers = ::std::move(rhs.m_buffers);
			return *this;
		}


		//---------------------------------------------------------------------
		// Adds a streambuf to the list
		//   return: new number of buffers
		//---------------------------------------------------------------------
		::std::size_t add_streambuf(base_streambuf_type *buf)
		{
			m_buffers.push_back(buf);
			return m_buffers.size();
		}

		//---------------------------------------------------------------------
		// Removes a streambuf
		//   return: new number of buffers
		//---------------------------------------------------------------------
		::std::size_t remove_streambuf(base_streambuf_type *buf)
		{
			auto pos = ::std::find(m_buffers.begin(), m_buffers.end(), buf);
			if(pos != m_buffers.end())
				m_buffers.erase(pos);

			return m_buffers.size();
		}


		//=====================================================================
		// Implementing interface of ::std::streambuf
		//=====================================================================

		//-----------------------------------------------------------
		// Changes the locale
		//---------------------------------------------------------------------
		void imbue(::std::locale const &loc)
		{
			for(auto buf: m_buffers)
				buf->pubimbue(loc);
		}

		//-----------------------------------------------------------
		// Since this streambuf is unbuffered (pptr() == nullptr),
		// this function is called at every output operation.
		//---------------------------------------------------------------------
		int_type overflow(int_type c)
		{
			if(c == traits_type::eof())
				return traits_type::not_eof(c);

			for(auto buffer: m_buffers)
				// sputc() either puts c in the internal buffer or calls
				// overflow() if the buffer is full or the stream is unbuffered.
				// In case of an error, either traits_type::eof() is returned or
				// an exception is thrown.
				if(buffer->sputc(c) == traits_type::eof())
					throw ::std::runtime_error("error while writing to streambuf");

			return c;
		}

	private:
		::std::vector<base_streambuf_type*> m_buffers;
	};

	typedef basic_containerbuf<char> containerbuf;
	typedef basic_containerbuf<wchar_t> wcontainerbuf;

} // namespace: io

using io::basic_containerbuf;
using io::containerbuf;
using io::wcontainerbuf;

} // namespace: light
